package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.example.demo.Utils.CreateJWT;
import com.example.demo.Utils.PasswordEncrypt;
import io.jsonwebtoken.Claims;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.dao.UserDao;
import com.example.demo.pojo.User;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;


	@Override
	public List<User> findUserList() {
		// TODO Auto-generated method stub
		List<User> userlist=new ArrayList<>();
		userlist=userDao.findUserList();
		System.out.println(userlist);
		return userlist;
	}


	/**
	 * 用户注册时持久化用户信息
	 * **/
	@Override
	public int registerAddUser(User user) {
		// TODO Auto-generated method stub
		System.out.println("添加用户...");
		int row;
		int result;
		//调用工具类对密码加密
		PasswordEncrypt passwordEncrypt=new PasswordEncrypt();
		String encode = passwordEncrypt.encrypt(user.getUserPassword());
		System.out.println("密码加密为"+encode);
		//将加密后的密码保存进数据库
		user.setUserPassword(encode);
		//角色和power已在数据库默认为对应字段内容
//		user.setUserPower("0");
//		user.setRole("101");
		row=userDao.registerAddUser(user);
		if(row>0) {
			//成功返回1
			result=1;
		}else {
			//失败返回0
			result=0;
		}
		return result;
	}

	/**
	 * 测试token
	 * **/
	@Override
	public String testToken(HttpServletRequest request, String userPassword){
		String result = null;
		Claims claims = null;
		CreateJWT createJWT = new CreateJWT();
		claims = createJWT.analysisToken(request,userPassword);
		System.out.println("测试结果--用户账号："+claims.getSubject()+"----"+"测试结果--用户密码"+claims.get("userPassword"));
		result = "测试结果--用户账号："+claims.getSubject()+"----"+"测试结果--用户密码"+claims.get("userPassword");
		return result;
	}


	/**
	 * 用户登录检测
	 * */
	@Override
	public String checkToken(Claims claims) {
		// TODO Auto-generated method stub
		System.out.println("token验证中...");
		String backInfo = null;
		String result;
		System.out.println("token中的账号："+claims.getSubject()+"----"+"token中的密码："+claims.get("userPassword"));
		backInfo=userDao.checkToken(claims.getSubject());
		System.out.println(userDao.checkToken(claims.getSubject()));
		System.out.println(backInfo);
		if(backInfo!=null) {
			result="ok";
		}else {
			result="bad";
		}
		return result;
	}

	/**
	* 用户重新登录发放token
	* */
	@Override
	public String createTokenAndLogin(String userAccount,String userPassword){
		String result = "";
		int msgFromDao = 0;
		String userTokenWeb = "";
		String role = null;
		String pwFromDao = null;
		boolean matchResult = false;
		//声明User类
		User user = new User();
		//声明token工具类
		CreateJWT createJWT = new CreateJWT();
		//声明密码加密解析工具类
		PasswordEncrypt passwordEncrypt = new PasswordEncrypt();
		//从dao层得到数据库中加密的密码、角色
		user = userDao.checkpw(userAccount);
		role = user.getRole();
		pwFromDao = user.getUserPassword();
		System.out.println("从数据库中得到的加密密码是："+pwFromDao+"----"+"角色是："+role);
		//匹配密码与加密密码
		matchResult = passwordEncrypt.match(userPassword,pwFromDao);
		System.out.println("service实现类中密码匹配结果："+matchResult);
		if(matchResult) {
			userTokenWeb = createJWT.createToken(userAccount, userPassword,role);
		}else{
			userTokenWeb = null;
		}
		//操作dao层
//		msgFromDao=userDao.createTokenAndLogin(userTokenWeb,userAccount);

		return userTokenWeb;
	}

	/**
	 * 查找用户基本信息功能接口
	 * */
	@Override
	public List<User> findUserBasicInfo(User user) {
		// TODO Auto-generated method stub
		System.out.println("查看user："+user);
		String userAccount;
		//实例化user对象
		User userInfo=new User();
		//得到用户账号
		userInfo.setUserAccount(user.getUserAccount());
		//将账号给userAccount
		userAccount=user.getUserAccount();
		//查看userinfo
		System.out.println(userInfo);
		List<User>list=userDao.findUserBasicInfo(userAccount);
		for(User info:list) {
			System.out.println("查看:"+info);
		}
		System.out.println("查看："+list);
		return list;
	}




	@Override
	public User findUserById(int id) {
		// TODO Auto-generated method stub
		return null;
	}


	/*
	 * 管理员修改用户信息功能接口
	 * */
	@Override
	public int backUserUpdataInfo(User user) {
		// TODO Auto-generated method stub
		int returnMSG=0;
		int msgFromDao;
		System.out.println("接收到的用户信息："+user);
		User userInfo=new User();
		try {
			msgFromDao=userDao.backUserUpdataInfo(user.getUserAccount(),user.getUserName(),user.getUserPower(),user.getUserProfile());
			System.out.println("dao层结果："+msgFromDao);
			if(msgFromDao>0) {
				returnMSG=1;
			}else {
				returnMSG=2;
			}
		} catch (Exception e) {
			System.out.println("异常！");
			returnMSG=0;
			// TODO: handle exception
		}
		return returnMSG;
	}


	/*
	 * 管理系统删除用户功能接口
	 * */
	@Override
	public int deleteUserFromBack(User user) {
		// TODO Auto-generated method stub
		int returnMSG=0;
		int msgFromDao;
		System.out.println("查看user："+user);
		User userInfo=new User();
		try {
			msgFromDao=userDao.deleteUserFromBack(user.getUserAccount(),user.getUserName());
			System.out.println("查看msgFromDao："+msgFromDao);
			if(msgFromDao>0) {
				//成功
				returnMSG=1;
			}else {
				//失败
				returnMSG=2;
			}
		} catch (Exception e) {
			//异常
			System.out.println("异常发生在deleteUserFromBack");
			returnMSG=0;
			// TODO: handle exception
		}
		return returnMSG;
	}


	@Override
	public int checkRegisterUserAccountRepeat(User user) {
		// TODO Auto-generated method stub
		int returnMSG=0;
		String msgFromDao;
		System.out.println("传来的用户信息"+user);
		User userInfo=new User();
		try {
			msgFromDao=userDao.checkRegisterUserAccountRepeat(user.getUserAccount());
			System.out.println("dao层返回的结果"+msgFromDao);
			if(msgFromDao!=null) {
				//不为空
				returnMSG=0;
			}else {
				//为空
				returnMSG=1;
			}
		} catch (Exception e) {
			//异常
			System.out.println("网络故障，请稍后再试！");
			returnMSG=0;
			// TODO: handle exception
		}
		return returnMSG;
	}

	/**
	 * 更改用户的启用状态（禁用、启用）
	 * **/
	@Override
	public int changeUserState(String userState, String userAccount) {
		int result = 0;
		try {
			System.out.println(userState+"\t"+userAccount);
			result = userDao.changeUserState(userState,userAccount);
			System.out.println(result);
			if(result > 0){
				return result;
			}
		}catch (Exception e){
			System.out.println("serviceImpl中的changeUserState发生异常:"+e);
			result = 0;
			return result;
		}
		return result;
	}
}
